package com.yzcrm.erp.wiki.service;


import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.math3.distribution.NormalDistribution;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.yzcrm.common.config.paragetter.BasePageRequest;
import com.yzcrm.erp.crm.common.CrmEnum;
import com.yzcrm.erp.wiki.entity.CareerAssessmentDimension;
import com.yzcrm.erp.wiki.entity.WikiCareerAssessment;
import com.yzcrm.erp.wiki.entity.WikiCareerAssessmentResult;
import com.yzcrm.utils.BaseUtil;
import com.yzcrm.utils.R;

/**
 * @author wyq
 */
public class WikiCareerAssessmentService {
    /**
     * 	@author lg
     *	获取题目
     */
    public R getCareerAssessmentSubjects(){
        List<Record> records = Db.find("select * from yzcrm_wiki_career_assessment_subject where type = 1 AND is_valid = 1 AND parent_subject_id = 0");
        ArrayList<Record> subjects = new ArrayList<Record>();
        if(records != null){
        	for(Record record : records) {
        		Record subject = new Record();
    			subject.set("subject_title",record.get("subject_title"))
    			.set("subject_id", record.get("subject_id"));
    			List<Record> subSubjects = Db.find("select subject_id,subject_title as option_title,0 AS option_value,sub_type from yzcrm_wiki_career_assessment_subject where type = 1 AND is_valid = 1 AND parent_subject_id = ?",record.getInt("subject_id"));
    			subject.set("subject_options", subSubjects);
    			subjects.add(subject);
        	}
        }
        Record oData = new Record();
        oData.set("subjects", subjects);
        return R.ok().put("data", oData);
    }
    
    /**
     * 	@author lg
     *	保存题目
     */
    public R setCareerAssessmentSubjects(JSONObject jsonObject){
    	WikiCareerAssessment wikiCareerAssessment = new WikiCareerAssessment();
    	CareerAssessmentDimension careerAssessmentDimension = jsonObject.getObject("subjectTotalValue", CareerAssessmentDimension.class);
    	Record record = Db.findFirst("select * from yzcrm_wiki_career_assessment where phone=?", jsonObject.getJSONObject("userInfo").getString("phone"));

    	try {
//        	保存基本信息
        	wikiCareerAssessment.setUsername(jsonObject.getJSONObject("userInfo").getString("username"));
        	wikiCareerAssessment.setPhone(jsonObject.getJSONObject("userInfo").getString("phone"));
        	if(record == null) {
        		wikiCareerAssessment.save();
        	}else {
        		return R.error("该用户已经提交过问卷，不能再提交");
        	}
        	
//        	保存用户填写的结果
        	JSONArray subjects = jsonObject.getJSONArray("subjects");
        	if(subjects.size() > 0 && wikiCareerAssessment.getCareerAssessmentId() != null) {
        		Db.delete("DELETE FROM yzcrm_wiki_career_assessment_middle where career_assessment_id = ?",wikiCareerAssessment.getCareerAssessmentId());
        		StringBuilder sql = new StringBuilder();
        		sql.append("INSERT INTO `yzcrm_wiki_career_assessment_middle` (career_assessment_id,subject_id,subject_value) VALUES ");
        		for(int i=0;i<subjects.size();i++) {
        			JSONObject sbj = (JSONObject) subjects.get(i);
        			sql.append("(").append(wikiCareerAssessment.getCareerAssessmentId() + "," + sbj.getInteger("subjectId") + "," + sbj.getInteger("optionValue"));
        			if(i == (subjects.size() - 1)) {
        				sql.append(");");
        			}else {
        				sql.append("),");
        			}
        		}
        		Db.update(sql.toString());
        	}
        	
//        	保存分析结果
    		int resultTotalNum = 0;
    		ArrayList<WikiCareerAssessmentResult> wikiCareerAssessmentResults = new ArrayList<WikiCareerAssessmentResult>();
    		for(Field field : careerAssessmentDimension.getClass().getDeclaredFields()) {
    			WikiCareerAssessmentResult wikiCareerAssessmentResult = new WikiCareerAssessmentResult();
    			String field_name = field.getName();
        		String field_value = field.get(careerAssessmentDimension).toString();
        		JSONObject careerData = handleCareerData(field_name,Integer.parseInt(field_value));
        		resultTotalNum += careerData.getInteger("resultNum");
        		wikiCareerAssessmentResult.setCareerAssessmentId(wikiCareerAssessment.getCareerAssessmentId());
        		wikiCareerAssessmentResult.setDimension(field_name);
        		wikiCareerAssessmentResult.setTotalNum(Integer.parseInt(field_value));
        		wikiCareerAssessmentResult.setNormdistValue(careerData.getBigDecimal("normdist_value"));
        		wikiCareerAssessmentResult.setExtremeNormdistValue(careerData.getBigDecimal("extreme_normdist_value"));
        		wikiCareerAssessmentResult.setResultNum(careerData.getInteger("resultNum"));
        		wikiCareerAssessmentResult.setResultStr(careerData.getString("resultStr"));
        		wikiCareerAssessmentResults.add(wikiCareerAssessmentResult);
        	}
    		//	一条语句批量插入
    		Db.delete("DELETE FROM yzcrm_wiki_career_assessment_result where career_assessment_id = ?",wikiCareerAssessment.getCareerAssessmentId());
    		Db.batchSave(wikiCareerAssessmentResults, wikiCareerAssessmentResults.size());
    		String assessment_result = resultTotalNum > 2 ? "低风险，较匹配" : resultTotalNum > 0 ? "有风险，需谨慎对待" : "高风险，不推荐";
    		wikiCareerAssessment.setAssessmentResultNum(resultTotalNum);
    		wikiCareerAssessment.setAssessmentResult(assessment_result);
    		wikiCareerAssessment.update();
		}catch (IllegalAccessException e) {
			e.printStackTrace();
		}
        return R.ok();
    }
    
    /**
     * 	@author lg
     * 	计算评估各个维度的值
     */
    public JSONObject handleCareerData(String type,int number) {
    	JSONObject jsonData = new JSONObject();
    	Record record = Db.findFirst("select value,description from yzcrm_admin_config where name = ?",type);
    	String[] constants = record.getStr("value").split(",");
//    	System.out.println(constants[0] + ":" + constants[1]);
//    	累计正态分布计算方法
    	NormalDistribution normalDistributioin = new NormalDistribution(Double.parseDouble(constants[1]),Double.parseDouble(constants[0]));
//    	正常情况的值
    	double normdist_value = Double.parseDouble(String.format("%.2f", normalDistributioin.cumulativeProbability(number)));
//    	极端情况的值
    	double extreme_normdist_value = normdist_value < 0.1 ? 0.1 : normdist_value > 0.99 ? 0.99 : normdist_value;
    	
    	String resultStr = null;
    	switch(type) {
	    	case "superiorityPower":
	    		resultStr = normdist_value > 0.85 ? "高风险" : normdist_value > 0.7 ? "风险" : "合适" ;
	    		break;
	    	case "recognitionAppreciation":
	    		resultStr = normdist_value >= 0.9 ? "风险" : normdist_value <= 0.1 ? "高风险" : normdist_value <= 0.25 ? "风险" : "合适" ;
	    		break;
	    	case "achievementsChallenges":
	    		resultStr = extreme_normdist_value <= 0.2 ? "高风险" : normdist_value <= 0.35 ? "风险" : "合适" ;
	    		break;
	    	case "intimacyConcern":
	    		resultStr = normdist_value <= 0.25 ? "风险" : "合适" ;
	    		break;
	    	case "growthLearning":
	    		resultStr = normdist_value <= 0.2 ? "风险" : "合适" ;
	    		break;
	    	case "inspireLife":
	    		resultStr = extreme_normdist_value >= 0.8 ? "高风险" : normdist_value >= 0.6 ? "风险" : "合适" ;
	    		break;
    	}
    	
    	Integer resultNum = resultStr == "风险" ? -1 : resultStr == "高风险" ? -2 : 1;
    	jsonData.put("normdist_value",normdist_value);
    	jsonData.put("extreme_normdist_value",extreme_normdist_value);
    	jsonData.put("resultStr",resultStr);
    	jsonData.put("resultNum",resultNum);
    	return jsonData;
    }
    
    
    /**
     * 	@author lg
     * 	获取个人分析报告
     */
    public R getAnalysisReport(String phone) {
    	JSONObject jsonData = new JSONObject();
    	List<Record> report = Db.find(Db.getSql("wiki.careerAssessment.getAnalysisReport"), phone);
    	jsonData.put("analysisReport", report);
    	return R.ok().put("data", jsonData);
    }
    
    
    public R getCareerAssessmentList(BasePageRequest basePageRequest) {
    	JSONObject jsonObject = basePageRequest.getJsonObject();
    	String search = jsonObject.getString("search");
    	Kv kv = new Kv();
    	kv.set("search", search);
    	kv.set("page", (basePageRequest.getPage() - 1) * basePageRequest.getLimit()).set("limit", basePageRequest.getLimit());
    	System.out.println(search + ";" + basePageRequest.getLimit() + ";" + basePageRequest.getPage());
    	List<Record> records = Db.find(Db.getSqlPara("wiki.careerAssessment.getCareerAssessmentList", kv));
    	SqlPara countSql = Db.getSqlPara("wiki.careerAssessment.getCareerAssessmentTotal", kv);
        Integer count = Db.queryInt(countSql.getSql(), countSql.getPara());
    	JSONObject careerAssessmentList = new JSONObject();
    	careerAssessmentList.put("careerAssessmentList",records);
    	careerAssessmentList.put("totalNum",count);
    	return R.ok().put("data",careerAssessmentList);
    }
    
    
}
